from flask import request, session
from flask_restful import Resource

from database import Database


# Mock user database

class InsertCart(Resource):
    def post(self):
        db = Database()
        username = session.get('username')

        data = request.get_json()
        bookId = data['bookId']

        # Check if the book is already in the cart
        existing_cart_entity = db.execute_query("SELECT * FROM cart WHERE bookId = %s AND userId = %s", (bookId, username))

        if existing_cart_entity:
            return {"message": "The book is already in the cart"}, 400
        else:
            # Add the book to the cart
            db.execute_query("INSERT INTO cart (bookId, userId) VALUES (%s, %s)", (bookId, username))
            return {"message": "Book added to cart successfully"}, 201